package com.dmai.capacity.platform.user.service.impl;

import com.dmai.capacity.platform.common.constant.CodeEnum;
import com.dmai.capacity.platform.common.constant.CommonConstant;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.PageResultData;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.constants.RoleTypeEnum;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import com.dmai.capacity.platform.user.mapper.SysOrganizationDao;
import com.dmai.capacity.platform.user.model.SysArea;
import com.dmai.capacity.platform.user.model.SysOrganization;
import com.dmai.capacity.platform.user.model.SysScopePermission;
import com.dmai.capacity.platform.user.pojo.response.InstitutionSimpleVO;
import com.dmai.capacity.platform.user.pojo.response.InstitutionVO;
import com.dmai.capacity.platform.user.service.ISysInstitutionService;
import com.dmai.capacity.platform.user.service.ISysOrganizationService;
import com.dmai.capacity.platform.user.service.ISysScopePermissionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;


@Service
public class SysOrganizationServiceImpl implements ISysOrganizationService {

    @Autowired
    private SysOrganizationDao sysOrganizationDao;

    @Autowired
    private ISysScopePermissionService scopePermissionService;

    @Autowired
    private ISysInstitutionService institutionService;


    /**
     * 添加
     *
     * @param sysOrganization
     */
    @Override
    public int save(SysOrganization sysOrganization) {
        sysOrganization.setStatus(1);
        sysOrganization.setUpdateTime(new Date());
        return sysOrganizationDao.save(sysOrganization);
    }

    /**
     * 修改
     *
     * @param sysOrganization
     */
    @Override
    public int update(SysOrganization sysOrganization) {
        sysOrganization.setUpdateTime(new Date());
        return sysOrganizationDao.update(sysOrganization);
    }


    /**
     * 删除
     *
     * @param id
     */
    @Override
    public int delete(String id) {
        SysOrganization orig = sysOrganizationDao.findById(id);
        if (orig == null) {
            throw new IllegalArgumentException("找不到对应的数据");
        }
        return sysOrganizationDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    @Override
    public SysOrganization findById(String id) {
        return sysOrganizationDao.findById(id);
    }

    @Override
    @Cacheable(value = "organization", unless = "#result == null")
    public String getFullName(String id) {
        SysOrganization self = sysOrganizationDao.findById(id);
        if (self == null) {
            return "";
        }
        if (self.getParentId().equals("-1")) {
            return self.getName();
        }
        return getFullName(self.getParentId()) + "/" + self.getName();
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SysOrganization> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT) != null && MapUtils.getInteger(params, CommonConstant.PAGE_SIZE) != null)
            PageHelper.startPage(MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT), MapUtils.getInteger(params, CommonConstant.PAGE_SIZE), true);


        List<SysOrganization> permissionList = getPermissionList(params);

        PageInfo<SysOrganization> pageInfo = new PageInfo(permissionList);

        return PageResult.<SysOrganization>builder().data(PageResultData.<SysOrganization>builder().records(pageInfo.getList()).total(pageInfo.getTotal()).pages(pageInfo.getPages()).build()).code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();

    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SysOrganization> findAll(Map<String, Object> params) {
        return getPermissionList(params);
    }

    private List<SysOrganization> getPermissionList(Map<String, Object> params) {
        LoginAppUser currentUser = AuthUtils.getLoginAppUser();
        List<SysOrganization> list = new ArrayList<>();
        Integer loadAll = MapUtils.getInteger(params, "loadAll");
        if (currentUser == null || (loadAll != null && 1 == loadAll)) {
            list = sysOrganizationDao.findAll(params);
        } else {
            // 数据权限判断
            List<SysScopePermission> permissions = scopePermissionService.findByUser(currentUser);

            if (CollectionUtils.isNotEmpty(permissions) && permissions.stream().filter(t -> t.getItemType().equalsIgnoreCase("ALL")).count() > 0) {
                // 全部机构权限
                list = sysOrganizationDao.findAll(params);
            } else if (CollectionUtils.isNotEmpty(permissions) && permissions.stream().filter(t -> t.getItemType().equalsIgnoreCase("ORG")).count() > 0) {
                // 当前及下级
                String organizationId = currentUser.getOrganizationId();
                if (RoleTypeEnum.INSTITUTION.getCode().equals(currentUser.getType())) {
                    InstitutionVO institution = institutionService.findById(Long.valueOf(currentUser.getOrganizationId()));
                    if (institution != null) {
                        organizationId = institution.getExamVenue();
                    }
                }

                params.put("parentId", organizationId);
                list = sysOrganizationDao.findAll(params);
            }
        }
        return list;
    }

}
